import http from '@/common/api/http.js'
import {
	baseUrl
} from '@/common/api/config.js'
import store from '@/common/store/index.js'
export default {
	data() {
		return {
			mxintimer: null,
			mxtriggered: false, // 下拉刷新
			osdbaseUrl: '',
			httpbaseUrl: baseUrl + '/',
			statusBarH: this.statusBar,
			customBarH: this.customBar,
			windowHeightH: this.windowHeight,
			mixinlatitude: '',
			listData: [],
			status: 'loadmore',
			loadingText: '努力加载中',
			loadmoreText: '轻轻上拉',
			nomoreText: '实在没有了',
			loadingPage: true
		}
	},
	onReachBottom() {
		if (this.searchForm?.page) {
			if (this.status != 'nomore') {
				this.searchForm.page++;
				this.getInfo(true);
			}
		}

	},
	methods: {
		$fail(title, duration = 3000) {
			uni.showToast({
				title,
				icon: 'none',
				duration
			})
		},
		// 跳转
		async $navTo(url, type = 'navigateTo') {
			// if(this.mixinlatitude == ''){
			// 	// let res =await this.$getLocation(1)
			// 	// if(res.location.lat){
			this.$newNavTo(url, type)
			// 	// }
			// 	this.$newNavTo(url, type)
			// }else{
			// 	this.$newNavTo(url, type)
			// }

		},
		$newNavTo(url, type) {
			if (!url) {
				return
			}
			let token = uni.getStorageSync('token')
			if (token) {
				uni.$u.route({
					url,
					type
				})
			} else {
				if (url == '/pages/contPackage/Invicinity/index' && (this.$store.state.labelStore.storuserInfoo.tagList
						.length == 0 || this.$store.state.labelStore.storuserInfo.headSculpture == '')) {
					if (this.$store.state.labelStore.storuserInfo.tagList.length == 0) {
						uni.showModal({
							title: '温馨提示',
							confirmColor: '#FFB400',
							cancelColor: '#999',
							content: '请完善个人标签信息',
							success(res) {
								if (res.confirm) {
									uni.redirectTo({
										url: '/pages/aPackage/persondata/index'
									})
								}
							}
						})
					} else {
						uni.showModal({
							title: '温馨提示',
							confirmColor: '#FFB400',
							cancelColor: '#999',
							content: '请完善个人信息',
							success(res) {
								if (res.confirm) {
									uni.redirectTo({
										url: '/pages/aPackage/userInfo/userInfo'
									})
								}
							}
						})
					}
				} else {
					uni.showModal({
						title: '温馨提示',
						confirmColor: '#FFB400',
						cancelColor: '#999',
						content: '未登录，请登录后使用',
						success(res) {
							if (res.confirm) {
								uni.redirectTo({
									url: '/pages/aPackage/login/index'
								})
							}
						}
					})
				}
			}
		},
		/**
		 * 跳转路径, 返回上一页
		 */
		$goBack() {
			let pages = getCurrentPages(); //获取所有页面栈实例列表
			let prevPage = pages[pages.length - 2]; //上一页页面实例
			if (prevPage) {
				uni.navigateBack()
			} else {
				uni.switchTab({
					url: '/pages/mainPackage/index/index'
				})
			}
		},

		/**
		 * 下拉刷新
		 */
		$refresherrefresh() {
			if (!this.mxtriggered) //界面下拉触发，triggered可能不是true，要设为true 
				this.mxtriggered = true;
			if (this.getResh) {
				this.getResh('refresh')
			}
			setTimeout(() => {
				this.mxtriggered = false; //触发onRestore，并关闭刷新图标 
			}, 200)
		},
		// 触底加载
		$handleLower() {
			if (this.getResh) {
				this.getResh('Lower')
			}
		},
		$formatter(type, value) {
			if (type === 'year') {
				return `${value}年`
			}
			if (type === 'month') {
				return `${value}月`
			}
			if (type === 'day') {
				return `${value}日`
			}
			if (type === 'hour') {
				return `${value}时`
			}
			if (type === 'minute') {
				return `${value}分`
			}
			return value
		},
		async $isLogin() {

		},
		async $initConfig(refresh = false) {

			let _this = this
			return new Promise(async (resolve, reject) => {
				let token = uni.getStorageSync('token') || ''
				let is_login = false
				if (refresh) {
					store.commit('logout')
					is_login = true
				} else {
					if (token) {
						let local_time = Date.now()
						if (((local_time - token.time) / 1000) > 5000) {
							console.log('已经过期了')
							is_login = true
						}
					} else {
						console.log('token不存在')
						is_login = true
					}
				}
				let app_info = uni.getSystemInfoSync()
				if (is_login) {
					// #ifdef MP-WEIXIN
					if (app_info.hostName == 'WeChat') { //小程序
						let ExternalUserID = uni.getStorageSync('ExternalUserID')
						let welcome_code = uni.getStorageSync('welcome_code')
						uni.login({
							provider: 'weixin', //使用微信登录
							success: function(loginRes) {
								http('login/loginApplet', {
									code: loginRes.code,
									ExternalUserID,
									welcome_code
								}).then(res => {
									if (res.code) {
										store.commit('login', res.data)
										resolve(res.data.data)
									}
								})
							}
						});
					} else if (app_info.hostName == 'wxwork') { //企业微信
						console.log('企业微信登录中')
						wx.qy.login({
							suiteId: 'ww1853b0f16864244b',
							success(wxCode) {
								http('login/checkLogin', {
									code: wxCode.code
								}).then(res => {
									if (res.code) {
										store.commit('login', res.data)
										resolve(res.data.data)
									}
								})
							}
						})
					}

					// #endif
				} else {
					resolve(token)
				}
			})
		},
		// 获取当前用户信息
		async $getUserInfo(isConnectSocet = true) {
			return new Promise(async (resolve, reject) => {
				try {
					let res = await this.$getApi('userInfo')
					let {
						success,
						data
					} = await this.$getApi('self_list')
					if (res.success) {
						let info = JSON.parse(res.data.info)
						const userId = res.data.id
						uni.getStorage({
							key: userId + '_history',
							success: (history) => {
								if (history.data) {
									this.$store.commit('INIT_CHAT', history.data)
								}
							}
						})
						uni.getStorage({
							key: userId + '_sendReadFail',
							success: (readHistory) => {
								if (readHistory.data) {
									this.$store.commit('SET_SEND_READ_FAIL', readHistory
										.data)
								}
							}
						})
						this.$store.commit('SET_USERID', userId)
						this.$store.commit('SET_USEINFO', {
							...res.data,
							tagList: data,
							...info
						})
						if (isConnectSocet && !this.$store.state.socket.socketOpen) {
							this.connectSocket()
						}
						resolve({
							...res.data,
							tagList: data,
							...info
						})
					}
				} catch (err) {
					reject(err)
				}
			})
		},
		//获取配置
		async $getHomeConfig() {
			return new Promise((resolve, reject) => {
				this.$getApi('group_query_home_config').then(res => {
					if (res.code == 200) {
						resolve(res.data)
					}
				})
			})
		},
		// 枚举
		async $getEnum(e, val = '/member') {
			return new Promise((resolve, reject) => {
				uni.request({
					url: this.$baseUrl + val + '/anon/getEnum/com.cj.' + e,
					method: 'get'
				}).then(res => {
					resolve(res.data)
				})
			})
		},
		/*
		  接受三个参数:params:可选,本地图片地址参数(默认) 或 服务器返回地址参数
		              server:可选,取值[true或false] true标识此参数是服务器返回的参数
		              type:  可选,取值[member,legwork,takeaway,socialize], 默认是legwork,标识将信息存储到那个服务器
		  */
		$uploadImgFn(params = '', apiName = 'ali_oss') { // type可选参数:member,legwork,takeaway,socialize
			return new Promise(async (resolve, reject) => {
				let imageTruePlace, imagePlace;
				// 传递了图片本地地址
				if (params) {
					let imgInfoPath = params;
					let res = await this.$getApi(apiName)
					let suffix = imgInfoPath?.substring(imgInfoPath?.lastIndexOf(".")); // 后缀
					if (res.code == 200) {
						let suffmessage = res.data
						suffmessage.key = suffmessage.key + suffix;
						let url = suffmessage.host
						delete suffmessage.host;
						delete suffmessage.sign;
						wx.uploadFile({
							filePath: imgInfoPath,
							name: 'file',
							url,
							header: {
								'content-type': 'multipart/form-data'
							},
							formData: suffmessage,
							success: (res) => {
								imagePlace = JSON.parse(res.data).data // 它是后台需要的地址数据
								resolve(imagePlace)
							},
							fail: (err) => {
								reject(err)
							}
						})
					}
				}
			})
		},
		/**
		 * 查看大图
		 */
		$showImgprview(url, arr, current = 0) {
			let urls = arr && arr.length ? arr.map(v => {
				return this.httpbaseUrl + v
			}) : [url]
			uni.previewImage({
				urls,
				current
			})
		},
		/**
		 * 保存图片到本地 filePath:接口返回的全路径
		 */
		$onSharetap(filePath) {
			let fileName = new Date().valueOf();
			let filePaths = wx.env.USER_DATA_PATH + '/' + fileName + '.jpg'
			wx.downloadFile({
				url: filePath,
				filePath: filePaths,
				success: (res) => {
					wx.saveImageToPhotosAlbum({
						filePath: res.filePath,
						success(res1) {
							wx.showToast({
								title: '图片保存成功！',
								icon: 'none'
							})
						},
						fail: function(res) {
							if (res.errMsg === "saveImageToPhotosAlbum:fail auth deny" || res
								.errMsg === "saveImageToPhotosAlbum:fail:auth denied") {
								that.doAuth()
							}
						}
					})
				}
			})
		},
		// 打电话
		$makePhoneCall(phoneNumber) {
			if (uni.$u.test.mobile(phoneNumber)) {
				uni.makePhoneCall({
					phoneNumber
				});
			} else {
				this.$fail('手机号不正确')
			}
		},
		/**
		 * 拍照
		 */
		$takePhoto(count, type = 1) {
			return new Promise((resolve, reject) => {
				uni.chooseImage({
					count,
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: type == 1 ? ['album', 'camera'] : type == 2 ? ['album'] : ['camera'],
					success: (res) => {
						if (res.tempFiles) {
							resolve(res.tempFiles)
						}
					}
				})
			})
		},
		$getLocation(e = 1) {
			let _this = this
			return new Promise((resolve, reject) => {
				wx.getLocation({
					type: "wgs84",
					success(res) {
						_this.mixinlatitude = res.latitude
						if (e == 1) {
							uni.request({
								url: 'https://apis.map.qq.com/ws/geocoder/v1',
								methods: 'get',
								data: {
									key: 'VEYBZ-Z5GC3-T3O35-3LQ3Z-6O4PS-GGBRU',
									location: res.latitude + ',' + res.longitude
								},
								success(res2) {
									if (res2.data.status == 0) {
										let address = res2.data.result.formatted_addresses
											.recommend
										resolve({
											...res2.data.result
										})
									}
								},
								fail(err) {
									reject('')
								}
							})
						} else if (e == 2) {
							wx.chooseLocation({
								latitude: res.latitude,
								longitude: res.longitude,
								success: async (resa) => {
									uni.request({
										url: 'https://apis.map.qq.com/ws/geocoder/v1',
										methods: 'get',
										data: {
											key: 'VEYBZ-Z5GC3-T3O35-3LQ3Z-6O4PS-GGBRU',
											location: res.latitude + ',' + res
												.longitude
										},
										success(res2) {
											if (res2.data.status == 0) {
												let address = res2.data.result
													.formatted_addresses
													.recommend
												resolve({
													resa,
													...res2.data.result,
													location: {
														lat: resa.latitude,
														lng: resa.longitude
													}
												})
											}
										},
										fail(err) {
											reject('')
										}
									})
								},
								fail: function(err) {
									// 用户取消选择位置或调用失败的回调函数
									reject(err);
								}
							})
						} else {
							resolve(res)
						}
					},
					fail(err) {
						if (_this.$refs.myToastref) {
							_this.$refs.myToastref.init('位置信息获取失败，是否重新设置', '提示', 1)
						}
						let userInfo = _this.$store.state.labelStore.storuserInfo
						resolve({
							location: {
								lat: userInfo.schoolLatitude,
								lng: userInfo.schoolLongitude
							},
							latitude: userInfo.schoolLatitude,
							longitude: userInfo.schoolLongitude
						})
					}
				})
			})
		},
		//定时器获取location
		async $getPosition() {
			try {

				let res = await this.$getLocation(3)
				let {
					success,
					msg
				} = await this.$getApi('position_edit', {
					latitude: res.latitude,
					longitude: res.longitude
				})
			} catch (err) {
				// clearInterval()
			}
		},
		//前端模糊搜索 ~方法 ：let arr = this.memmerList.filter(this.$createFilter(e,'nickName'))
		$createFilter(queryString, val) {
			return (restaurant) => {
				return (restaurant[val].toLowerCase().indexOf(queryString.toLowerCase()) === 0);
			};
		},
		// 数组对象去重
		$reduceTab(arr, val) {
			let newobj = {};
			let newArr = arr.reduce((preVal, curVal) => {
				newobj[curVal[val]] ? '' : newobj[curVal[val]] = preVal.push(curVal);
				return preVal
			}, [])
			return newArr
		},
		$showModal(content = '努力开发中，敬请期待~') {
			uni.showModal({
				content,
				confirmColor: '#FFB400',
				showCancel: false
			})
		},
		$setClipboardData(text) {
			let _this = this
			wx.setClipboardData({
				data: text,
				success: function() {
					_this.$fail('复制成功')
				},
				fail: function() {
					_this.$fail('复制失败')
				}
			});
		},
		// 转换价格
		$calcPrice(e) {
			if (e == '' || e == null || e == undefined) {
				return
			}
			let arr = e.split('.')
			let str = `<span style="font-size:40rpx;">${arr[0]}</span>.${arr[1]}`
			return str
		}
	}
}